package com.bifang.common.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import com.bifang.common.constant.ConstantValue;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import org.apache.commons.lang3.StringUtils;

/** 通用加解密 */
public class CommonSecureUtil {
    public static String aesEncrypt(String str) {
        return StringUtils.isBlank(str)
                ? str
                : SecureUtil.aes(Base64.decode(ConstantValue.default_aes_key))
                        .encryptBase64(str, Charset.forName("UTF-8"));
    }

    public static String aesDecrypt(String str) {
        try {
            return StringUtils.isBlank(str)
                    ? str
                    : SecureUtil.aes(Base64.decode(ConstantValue.default_aes_key))
                            .decryptStr(str, Charset.forName("UTF-8"));
        } catch (Exception e) {
            return str;
        }
    }

    public static String shaEncrypt(String inStr) throws Exception {
        MessageDigest sha = null;
        try {
            sha = MessageDigest.getInstance("SHA");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        byte[] byteArray = inStr.getBytes("UTF-8");
        byte[] md5Bytes = sha.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }
}
